package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
　　* @description: TODO
　　* @author shenrm
　　* @date 2021/11/4 11:44
　　*/
@Component
public class FlowApplyUserComponentUtil {

    @Autowired
    private RuntimeService runtimeService;

    /**
     * 根据流程实例ID获取拟稿人(发启动人)的ID
     * @param processInstanceId
     * @param applyUser
     * @return
     */
    public String getApplyUser(String processInstanceId, String applyUser) {
        String userId = "";
        if(StringUtils.isNotBlank(applyUser)) {
            userId = applyUser;
        } else {
            // 根据流程实例ID获取拟稿人ID
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            if (Objects.nonNull(processInstance)) {
                List<Execution> executionList = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).list();
                if (Objects.nonNull(executionList) && !executionList.isEmpty()) {
                    String executionId = executionList.get(0).getId();
                    Object initiatorObj = runtimeService.getVariable(executionId, "assigned_apply_initiator");
                    if (Objects.nonNull(initiatorObj) && (initiatorObj instanceof String)){
                        //获取流程发起人
                        userId = String.valueOf(initiatorObj);
                    }
                }
            }
        }
        return userId;
    }
}
